/*!
 * \file test_wts_object_base.cpp
 * \project WonderTrader
 *
 * \author AI Assistant
 * \date 2024/12/19
 * 
 * \brief WTS基础对象测试文件
 * 
 * \details 测试WTS核心基础类的功能：
 *          - WTSObject：基础对象和引用计数测试
 *          - 内存管理机制测试
 *          - 对象生命周期管理测试
 *          - 多线程安全性测试
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <memory>
#include <string>
#include <vector>
#include <thread>
#include <chrono>
#include <atomic>

#include "../../src/Includes/WTSObject.hpp"

using namespace wtp;

/*!
 * \class TestWTSObject
 * \brief 测试用的WTSObject派生类
 * 
 * \details 用于测试WTSObject基础功能的简单派生类
 */
class TestWTSObject : public WTSObject {
public:
    TestWTSObject(int value = 0) : m_value(value), m_destroyed(false) {}
    
    virtual ~TestWTSObject() {
        m_destroyed = true;
    }
    
    int getValue() const { return m_value; }
    void setValue(int value) { m_value = value; }
    bool isDestroyed() const { return m_destroyed; }
    
private:
    int m_value;
    bool m_destroyed;
};

/*!
 * \class WTSObjectBaseTest
 * \brief WTS基础对象测试类
 * 
 * \details 测试WTS基础对象的所有核心功能
 */
class WTSObjectBaseTest : public ::testing::Test {
protected:
    void SetUp() override {
        // 测试前准备工作
    }

    void TearDown() override {
        // 测试后清理工作
    }
};

/*!
 * \brief 测试WTSObject基本功能
 * 
 * \details 验证WTSObject的基本创建和销毁：
 *          - 对象创建
 *          - 初始引用计数
 *          - 基本属性访问
 */
TEST_F(WTSObjectBaseTest, TestWTSObjectBasicOperations) {
    // 测试对象创建
    TestWTSObject* obj = new TestWTSObject(42);
    ASSERT_NE(obj, nullptr);
    
    // 验证初始状态
    EXPECT_EQ(obj->getValue(), 42);
    EXPECT_FALSE(obj->isDestroyed());
    EXPECT_EQ(obj->retainCount(), 1);  // 初始引用计数为1
    
    // 测试属性修改
    obj->setValue(100);
    EXPECT_EQ(obj->getValue(), 100);
    
    // 测试引用计数操作
    obj->retain();
    EXPECT_EQ(obj->retainCount(), 2);
    
    obj->retain();
    EXPECT_EQ(obj->retainCount(), 3);
    
    // 测试release操作
    obj->release();
    EXPECT_EQ(obj->retainCount(), 2);
    
    obj->release();
    EXPECT_EQ(obj->retainCount(), 1);
    
    // 最后一次release会销毁对象
    obj->release();
    // 注意：此时obj指针已无效，不能再访问
}

/*!
 * \brief 测试WTSObject引用计数机制
 * 
 * \details 验证WTSObject的引用计数功能：
 *          - 初始引用计数
 *          - 引用计数增减
 *          - 自动销毁机制
 *          - 引用计数边界条件
 */
TEST_F(WTSObjectBaseTest, TestWTSObjectReferenceCount) {
    TestWTSObject* obj = new TestWTSObject(123);
    ASSERT_NE(obj, nullptr);
    
    // 验证初始引用计数
    EXPECT_EQ(obj->retainCount(), 1);
    EXPECT_TRUE(obj->isSingleRefs());  // 引用计数为1时是单一引用
    
    // 增加引用计数
    obj->retain();
    EXPECT_EQ(obj->retainCount(), 2);
    EXPECT_FALSE(obj->isSingleRefs());
    
    obj->retain();
    EXPECT_EQ(obj->retainCount(), 3);
    EXPECT_FALSE(obj->isSingleRefs());
    
    // 减少引用计数
    obj->release();
    EXPECT_EQ(obj->retainCount(), 2);
    EXPECT_FALSE(obj->isSingleRefs());
    
    obj->release();
    EXPECT_EQ(obj->retainCount(), 1);
    EXPECT_TRUE(obj->isSingleRefs());  // 引用计数为1时是单一引用
    
    // 最后一次release
    obj->release();
    // 对象已被销毁
}

/*!
 * \brief 测试WTSObject内存管理
 * 
 * \details 验证WTSObject的内存管理机制：
 *          - 大量对象创建和销毁
 *          - 内存泄漏检测
 *          - 引用计数正确性
 */
TEST_F(WTSObjectBaseTest, TestWTSObjectMemoryManagement) {
    const int object_count = 1000;
    std::vector<TestWTSObject*> objects;
    
    // 创建大量对象
    for (int i = 0; i < object_count; ++i) {
        TestWTSObject* obj = new TestWTSObject(i);
        ASSERT_NE(obj, nullptr);
        EXPECT_EQ(obj->retainCount(), 1);
        EXPECT_EQ(obj->getValue(), i);
        objects.push_back(obj);
    }
    
    // 验证所有对象都创建成功
    EXPECT_EQ(objects.size(), object_count);
    
    // 增加所有对象的引用计数
    for (auto* obj : objects) {
        obj->retain();
        EXPECT_EQ(obj->retainCount(), 2);
    }
    
    // 减少引用计数
    for (auto* obj : objects) {
        obj->release();
        EXPECT_EQ(obj->retainCount(), 1);
    }
    
    // 最终释放所有对象
    for (auto* obj : objects) {
        obj->release();
    }
    
    // 如果没有内存泄漏，测试应该正常完成
    SUCCEED();
}

/*!
 * \brief 测试WTSObject多线程安全性
 * 
 * \details 验证WTSObject在多线程环境下的安全性：
 *          - 并发引用计数操作
 *          - 线程安全的retain/release
 *          - 并发对象创建
 */
TEST_F(WTSObjectBaseTest, TestWTSObjectThreadSafety) {
    const int num_threads = 8;
    const int operations_per_thread = 1000;
    
    TestWTSObject* shared_obj = new TestWTSObject(999);
    ASSERT_NE(shared_obj, nullptr);
    
    // 预先增加引用计数，确保对象在测试期间不会被销毁
    for (int i = 0; i < num_threads; ++i) {
        shared_obj->retain();
    }
    
    std::vector<std::thread> threads;
    std::atomic<int> total_operations(0);
    
    // 启动多个线程并发操作引用计数
    for (int i = 0; i < num_threads; ++i) {
        threads.emplace_back([&, i]() {
            for (int j = 0; j < operations_per_thread; ++j) {
                // 随机进行retain或release操作
                if (j % 2 == 0) {
                    shared_obj->retain();
                } else {
                    shared_obj->release();
                }
                total_operations++;
            }
        });
    }
    
    // 等待所有线程完成
    for (auto& t : threads) {
        t.join();
    }
    
    // 验证操作总数
    EXPECT_EQ(total_operations.load(), num_threads * operations_per_thread);
    
    // 验证对象仍然有效
    EXPECT_EQ(shared_obj->getValue(), 999);
    EXPECT_GT(shared_obj->retainCount(), 0);
    
    // 清理：释放预先增加的引用计数
    for (int i = 0; i < num_threads; ++i) {
        shared_obj->release();
    }
    
    // 最终释放对象
    shared_obj->release();
}

/*!
 * \brief 测试WTSObject边界条件
 * 
 * \details 验证WTSObject在边界条件下的行为：
 *          - 极限引用计数
 *          - 异常情况处理
 */
TEST_F(WTSObjectBaseTest, TestWTSObjectBoundaryConditions) {
    TestWTSObject* obj = new TestWTSObject(0);
    ASSERT_NE(obj, nullptr);
    
    // 测试大量retain操作
    const int large_retain_count = 10000;
    for (int i = 0; i < large_retain_count; ++i) {
        obj->retain();
    }
    
    EXPECT_EQ(obj->retainCount(), large_retain_count + 1);  // +1是初始计数
    
    // 测试大量release操作
    for (int i = 0; i < large_retain_count; ++i) {
        obj->release();
    }
    
    EXPECT_EQ(obj->retainCount(), 1);
    EXPECT_TRUE(obj->isSingleRefs());
    
    // 最终释放
    obj->release();
}

/*!
 * \brief 测试WTSObject性能特性
 * 
 * \details 验证WTSObject的性能表现：
 *          - 创建销毁性能
 *          - 引用计数操作性能
 *          - 内存使用效率
 */
TEST_F(WTSObjectBaseTest, TestWTSObjectPerformance) {
    const int performance_count = 100000;
    
    // 测试对象创建性能
    auto start = std::chrono::high_resolution_clock::now();
    
    std::vector<TestWTSObject*> objects;
    objects.reserve(performance_count);
    
    for (int i = 0; i < performance_count; ++i) {
        TestWTSObject* obj = new TestWTSObject(i);
        objects.push_back(obj);
    }
    
    auto end = std::chrono::high_resolution_clock::now();
    auto creation_duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
    
    std::cout << "创建 " << performance_count << " 个对象耗时: " 
              << creation_duration.count() << "ms" << std::endl;
    
    // 测试引用计数操作性能
    start = std::chrono::high_resolution_clock::now();
    
    for (auto* obj : objects) {
        obj->retain();
        obj->retain();
        obj->release();
        obj->release();
    }
    
    end = std::chrono::high_resolution_clock::now();
    auto refcount_duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
    
    std::cout << "执行 " << performance_count * 4 << " 次引用计数操作耗时: " 
              << refcount_duration.count() << "ms" << std::endl;
    
    // 测试对象销毁性能
    start = std::chrono::high_resolution_clock::now();
    
    for (auto* obj : objects) {
        obj->release();
    }
    
    end = std::chrono::high_resolution_clock::now();
    auto destruction_duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
    
    std::cout << "销毁 " << performance_count << " 个对象耗时: " 
              << destruction_duration.count() << "ms" << std::endl;
    
    // 验证性能在合理范围内
    EXPECT_LT(creation_duration.count(), 1000);     // 创建应该小于1秒
    EXPECT_LT(refcount_duration.count(), 500);      // 引用计数操作应该小于0.5秒
    EXPECT_LT(destruction_duration.count(), 1000);  // 销毁应该小于1秒
}

/*!
 * \brief 测试WTSObject派生类功能
 * 
 * \details 验证WTSObject派生类的特殊功能：
 *          - 虚函数调用
 *          - 多态性
 *          - 派生类特有功能
 */
TEST_F(WTSObjectBaseTest, TestWTSObjectDerivedClass) {
    // 创建派生类对象
    TestWTSObject* derived_obj = new TestWTSObject(777);
    ASSERT_NE(derived_obj, nullptr);
    
    // 测试派生类特有功能
    EXPECT_EQ(derived_obj->getValue(), 777);
    EXPECT_FALSE(derived_obj->isDestroyed());
    
    // 测试基类功能
    EXPECT_EQ(derived_obj->retainCount(), 1);
    derived_obj->retain();
    EXPECT_EQ(derived_obj->retainCount(), 2);
    
    // 测试多态性 - 通过基类指针访问
    WTSObject* base_ptr = derived_obj;
    EXPECT_EQ(base_ptr->retainCount(), 2);
    
    base_ptr->retain();
    EXPECT_EQ(base_ptr->retainCount(), 3);
    EXPECT_EQ(derived_obj->retainCount(), 3);  // 同一个对象
    
    // 测试虚析构函数
    base_ptr->release();
    base_ptr->release();
    base_ptr->release();  // 应该正确调用派生类析构函数
}

/*!
 * \brief 测试WTSObject完整生命周期
 * 
 * \details 验证WTSObject的完整生命周期管理：
 *          - 创建 -> 使用 -> 共享 -> 释放 -> 销毁
 *          - 复杂引用关系管理
 */
TEST_F(WTSObjectBaseTest, TestWTSObjectCompleteLifecycle) {
    // 模拟复杂的对象生命周期管理场景
    std::vector<TestWTSObject*> object_pool;
    std::vector<std::vector<TestWTSObject*>> shared_references;
    
    const int pool_size = 50;
    const int reference_groups = 10;
    
    // 阶段1：创建对象池
    for (int i = 0; i < pool_size; ++i) {
        TestWTSObject* obj = new TestWTSObject(i * 10);
        object_pool.push_back(obj);
    }
    
    // 阶段2：创建共享引用组
    shared_references.resize(reference_groups);
    for (int group = 0; group < reference_groups; ++group) {
        for (int i = 0; i < pool_size; i += (group + 1)) {
            TestWTSObject* obj = object_pool[i];
            obj->retain();  // 增加引用计数
            shared_references[group].push_back(obj);
        }
    }
    
    // 阶段3：验证引用计数正确性
    for (int i = 0; i < pool_size; ++i) {
        int expected_refs = 1;  // 初始引用
        
        // 计算期望的引用计数
        for (int group = 0; group < reference_groups; ++group) {
            if (i % (group + 1) == 0) {
                expected_refs++;
            }
        }
        
        EXPECT_EQ(object_pool[i]->retainCount(), expected_refs);
    }
    
    // 阶段4：释放共享引用
    for (int group = 0; group < reference_groups; ++group) {
        for (auto* obj : shared_references[group]) {
            obj->release();
        }
        shared_references[group].clear();
    }
    
    // 阶段5：验证引用计数恢复到初始状态
    for (auto* obj : object_pool) {
        EXPECT_EQ(obj->retainCount(), 1);
        EXPECT_TRUE(obj->isSingleRefs());
    }
    
    // 阶段6：最终清理
    for (auto* obj : object_pool) {
        obj->release();
    }
    
    std::cout << "对象完整生命周期测试通过" << std::endl;
    std::cout << "管理了 " << pool_size << " 个对象" << std::endl;
    std::cout << "创建了 " << reference_groups << " 个引用组" << std::endl;
} 